package com.pig.openg1.graphics;

import android.content.Context;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.util.AttributeSet;
import android.util.Log;

import com.pig.openg1.data.Cube;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

/****
 * 绘制正方体
 */
public class DrawView2  extends GLSurfaceView {

    private Cube cube;

    public DrawView2(Context context) {
        super(context);
        init();
    }

    public DrawView2(Context context, AttributeSet attrs) {
        super(context, attrs);
         init();
    }

    private void init()
    {
        setEGLContextClientVersion(2);
        setRenderer(new CubeRender());
        //主动模式
        setRenderMode(RENDERMODE_CONTINUOUSLY);
    }


    private class CubeRender implements Renderer{



        @Override
        public void onSurfaceCreated(GL10 gl, EGLConfig config) {
            //设置背景色
            GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1);
            //开启深度测试
            //为什么我不用深度测试，我的3D图形看起来就缺面
            //深度测试决定着绘制的先后顺序
//            GLES20.glIsEnabled(GLES20.GL_DEPTH_TEST);
            cube = new Cube();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true)
                    {
                        cube.angle =  cube.angle + 2F;
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            Log.e("DrawView2","线程执行失败：" + e.getMessage());
                        }
                    }

                }
            }).start();

        }

        @Override
        public void onSurfaceChanged(GL10 gl, int width, int height) {

            GLES20.glViewport(0,0,width,height);
            //设置宽高比
            float ratio = (float)width/height;
            //透视投影
            Matrix.frustumM(Cube.mProjMatrix,0,-ratio,ratio,-1,1,2,20);
            //设置相机

            Matrix.setLookAtM(Cube.mVMatrix, 0,
                    5, 5, 5,
                    0, 0, 0,
                    1, 1, 0);

        }

        @Override
        public void onDrawFrame(GL10 gl) {

            //清除颜色和深度缓存
            GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
            cube.drawSelf();

        }
    }

}
